package com.example.demo.demos.rest;

import io.modelcontextprotocol.client.McpAsyncClient;
import io.modelcontextprotocol.spec.McpSchema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.util.Map;

@RestController
public class McpClientDemo {
    @Autowired
    private McpClientDetectAutoConfig.McpAsyncClientsWrapper mcpAsyncClientsWrapper;

    @RequestMapping("/mcpsend")
    public String mcpsend() {
        String sss = "" + System.currentTimeMillis();

        McpAsyncClient client = mcpAsyncClientsWrapper.get("server1");
        Mono<McpSchema.CallToolResult> toolresult = client.callTool(new McpSchema.CallToolRequest("getWeather", Map.of("cityName", "wuhan")));


        Mono<McpSchema.GetPromptResult> promotresult = client.getPrompt(new McpSchema.GetPromptRequest("greeting", Map.of("name", "wuhanpeople")));
//                Mono<McpSchema.CompleteResult> completionresult = client.completeCompletion(new McpSchema.CompleteRequest(new McpSchema.PromptReference("code-completion")
//                        , new McpSchema.CompleteRequest.CompleteArgument("java", "main")));
        Mono<McpSchema.ReadResourceResult> resourceResultMono = client.readResource(new McpSchema.ReadResourceRequest("test.txt"));
// 使用 zip 组合所有任务，并在全部完成后组装结果
        String ss1 = Mono.zip(toolresult
                        , promotresult
                        , resourceResultMono
//                                , completionresult
                )
                .map(tuple -> {
                    String ss = "-RESULT-" + client.getServerInfo().name();
                    McpSchema.CallToolResult t1 = tuple.getT1();
                    McpSchema.GetPromptResult p1 = tuple.getT2();
                    McpSchema.ReadResourceResult r1 = tuple.getT3();
//                            McpSchema.CompleteResult c1 = tuple.getT4();
                    for (McpSchema.Content content : t1.content()) {
                        ss += ",CallToolResult::" + content;
                    }
                    for (McpSchema.PromptMessage content : p1.messages()) {
                        ss += ",GetPromptResult::" + content;
                    }
//                            for (String content : c1.completion().values()) {
//                                ss += ",CompleteResult::" + content;
//                            }
                    for (McpSchema.ResourceContents content : r1.contents()) {
                        ss += ",ReadResourceResult::" + content;
                    }
                    return ss;
                })
                .block(); // 返回 Mono<Void>
        // 触发执行（生产环境应避免 block）
        sss += ss1;
        return sss;
    }
}
